package org.bangumibuddy.mock.httpserver.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import lombok.SneakyThrows;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public class TorrentHandler implements HttpHandler {
    @Override
    @SneakyThrows
    public void handle(HttpExchange exchange) throws IOException {
        if ("HEAD".equals(exchange.getRequestMethod())) {
            String filePath = exchange.getRequestURI().getPath();
            if (Files.exists(Path.of(getClass().getResource(filePath).toURI()))) {
                exchange.sendResponseHeaders(200, -1); // 200 OK, no response body
            } else {
                exchange.sendResponseHeaders(404, -1); // 404 Not Found, no response body
            }
            exchange.close();
            return;
        }

        // Step 1: Get the request URI
        String requestPath = exchange.getRequestURI().getPath();

        // Step 2: Split the path into parts
        String[] pathParts = requestPath.split("/");

        // Step 3: Get the filename from the last part of the path
        String filename = pathParts[pathParts.length - 1];


        // Read the file content
        byte[] fileContent = Files.readAllBytes(Path.of(getClass().getResource("/torrents/" + filename).toURI()));

        // Set the response headers
        exchange.getResponseHeaders().set("Content-Type", "application/x-bittorrent");
        exchange.sendResponseHeaders(200, fileContent.length);

        // Write the file content to the response body
        OutputStream responseBody = exchange.getResponseBody();
        responseBody.write(fileContent);

        // Close the output stream and the exchange
        responseBody.close();
    }
}
